package cn.endeavour.basic.util;

import cn.endeavour.user.domain.LoginInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录上下文
 * 1.获取当前登录人的信息
 * 2.当前当路人的权限 - 现在不写
 */
public class LoginContextUtil {

    public static LoginInfo getLoginInfo(HttpServletRequest request) {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            //获取Spring容器对象
            WebApplicationContext context
                    = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            //获取redisTemplate对象，因为登录信息在redis中，必须通过这个对象才能获取redis的数据
            RedisTemplate redisTemplate = context.getBean("redisTemplate", RedisTemplate.class);
            Object object = redisTemplate.opsForValue().get(token);
            if (object != null) {
                return (LoginInfo) object;
            }
        }
        return null;
    }
}